package com.example.app.webview.web

import android.content.Context
import android.webkit.JavascriptInterface
import android.webkit.WebView
import com.blankj.utilcode.util.LogUtils
import com.blankj.utilcode.util.ToastUtils
import com.example.app.global.GlobalUserManager
import com.gyf.immersionbar.ImmersionBar
import com.libcommon.LiveEventManager
import com.libcommon.MoshiManager
import org.json.JSONObject


/**
 * 说明: js 调原生端操作
 */
class JavaScriptHandler(webView: WebView) {

    companion object {
        private const val TAG = "JavaScriptHandler"
        private const val CLICK_TIME = 500L
    }

    private val context: Context
    private val webView: WebView

    private var lastClickTime = 0L

    /**
     * js调原生
     * @param jsonStr 传递数据 jsonStr
     */
    @Suppress("SameReturnValue")
    @JavascriptInterface
    fun call(jsonStr: String?): String {
        LogUtils.dTag(TAG, "jsonStr = $jsonStr")
        if (jsonStr.isNullOrEmpty()) return ""
        try {
            val jsonObj = JSONObject(jsonStr)
            val action = jsonObj.optString("action")
            val dataObj = jsonObj.optJSONObject("data")
            when (action) {
                JsCMD.webGoBack -> LiveEventManager.post(EventWeb(JsCMD.webGoBack))
                JsCMD.webClose -> LiveEventManager.post(EventWeb(JsCMD.webClose))

                JsCMD.webRefresh -> LiveEventManager.post(EventWeb(JsCMD.webRefresh))
                JsCMD.showToast -> {
                    val message = dataObj?.optString("message") ?: ""
                    ToastUtils.showShort(message)
                }

                JsCMD.statusBarHigh -> return "${ImmersionBar.getStatusBarHeight(context)}"
                JsCMD.getUid -> return GlobalUserManager.getUid().toString()
            }
        } catch (e: Exception) {
            e.printStackTrace()
        }
        return ""
    }

    /**
     * 原生调JS
     * @param bean   CallBackJsBean json
     */
    fun callJs(bean: CallBackJsBean) {
        webView.post {
            webView.loadUrl("javascript:window.sendAppJsInfo(${MoshiManager.toJson(bean)})")
        }
    }

    init {
        context = webView.context
        this.webView = webView
    }
}